package light.head.controller.mobile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.mobile.MobileGoodsApplyDAO;
import light.head.dao.mobile.MobileGoodsApplyItemDAO;
import light.head.dao.oa.AuditStatusDAO;
import light.head.dao.oa.ProcessConfigDAO;
import light.head.dao.sys.MessageDAO;
import light.head.dao.sys.MessageTemplateDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.ApplyInfo;
import light.head.model.ApplyItem;
import light.head.model.AuditStatus;
import light.head.model.ProcessConfig;
import light.head.model.UserInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * 物品申请
 * @author yangguanghe @date 2014-5-20 @time 下午5:47:32
 *
 */
@Controller
@RequestMapping(Url.MOBILE_GOODSAPPLY)
public class MobileGoodsApplyController extends SupporterController {

	private MobileGoodsApplyDAO goodsApplyDAO;
	private MobileGoodsApplyItemDAO applyItemDAO;
	private ProcessConfigDAO processConfigDAO;
	private AuditStatusDAO auditStatusDAO;
	private UserInfoDAO userDAO;
	private MessageDAO msgDAO;
	private MessageTemplateDAO mtDAO;
	
	@RequestMapping(Url.INIT)
	public ModelAndView init (HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.MOBILE_GOODSAPPLY_INIT);
	}
	
	@RequestMapping(Url.QUERY)
	public ModelAndView list (HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pb = createPageBean(request);
		Map<String,String> map = createQueryMapByParmName(request, Parm.TITLE, Parm.ST, Parm.ET);
		
		goodsApplyDAO.findByMap(cu_code(request), map, pb);
		
		if (null != pb.getResultList()) {
			
			List<Integer> acs = new ArrayList<Integer>();
			ApplyInfo applyInfo = null;
			
			for (Object obj : pb.getResultList()) {
				applyInfo = (ApplyInfo) obj;
				acs.add(applyInfo.getCode());
				// 审核状态
				if (null != applyInfo.getSort() && applyInfo.getSort().byteValue() == Sys.B_TWO) {
					applyInfo.setAuditStatusList(auditStatusDAO.findByBusinessMc(Sys.B_ONE, applyInfo.getCode()));
				}
			}
			List<ApplyItem> itemList = applyItemDAO.findByApplyCode(acs);
			
			for (Object obj : pb.getResultList()) {
				applyInfo = (ApplyInfo) obj;
				for (ApplyItem item : itemList) {
					if (applyInfo.getCode().intValue() == item.getAcode().intValue()) {
						applyInfo.addItem(item);
					}
				}
			}
			
			
			
			
		}
		
		request.setAttribute(Parm.PAGE_BEAN, pb);
		return new ModelAndView(Url.MOBILE_GOODSAPPLY_LIST);
	}
	
	@RequestMapping(Url.EDIT)
	public ModelAndView edit (HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		ApplyInfo info = null;
		if (isNotNull(code)) {
			info = goodsApplyDAO.get(Integer.parseInt(code));
			if (null != info) {
				info.setAdList(applyItemDAO.findByApplyCode(info.getCode()));
			}
		}
		request.setAttribute(Parm.INFO, info);
		return new ModelAndView(Url.MOBILE_GOODSAPPLY_EDIT);
	}
	
	@RequestMapping(Url.EDIT_SHOW)
	public ModelAndView editShow (HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		ApplyInfo info = null;
		if (isNotNull(code)) {
			info = goodsApplyDAO.get(Integer.parseInt(code));
			if (null != info) {
				info.setAdList(applyItemDAO.findByApplyCode(info.getCode()));
			}
		}
		request.setAttribute(Parm.INFO, info);
		return new ModelAndView(Url.MOBILE_GOODSAPPLY_EDIT_SHOW);
	}
	
	@RequestMapping(Url.SHIELD)
	public void shield (HttpServletRequest request, HttpServletResponse response) throws Exception {
		String code = request.getParameter(Parm.CODE);
		
		if (isNotNull(code)) {
			ApplyInfo info = goodsApplyDAO.get(Integer.parseInt(code));
			if (null == info) {
				print(response, Msg.NOT_FIND);
				return;
			}
			
			// 判断是否是固定资产，
			if (info.getSort().byteValue() == Sys.B_TWO) {
				// 判断是否已经被审核
				if(auditStatusDAO.checkIsAudit(Sys.B_ONE, info.getCode())) {
					print(response, Msg.FAILURE);
					return;
				}
			}
			
			info.setDeleted(true);
			if (RESULT.SUCCESS == goodsApplyDAO.upd(info))
				print(response, Msg.SUCCESS);
			else 
				print(response, Msg.ERROR);
			
			return;
		}
		
		print(response, Msg.ERROR);
	}
	
	
	@Transactional(rollbackFor = Exception.class)
	@RequestMapping(Url.SAVE)
	public void save (ApplyInfo info, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		if (null == info) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		Boolean ok = null;
		for (ApplyItem item : info.getAdList()) {
			ok = true;
			if (null != item && !Sys.NONE.equals(item.getGn()) && null != item.getCount() && item.getCount().intValue() > 0) {
				ok = false;
				break;
			}
		}
		
		if (ok) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		
		RESULT result = RESULT.ERROR;
		
		Date time = new Date();
		Integer cuCode = cu_code(request);
		Integer cuOrganCode = cu_organCode(request);
		
		boolean isadd = false;	// 是否是添加
		// 保存，
		if (null != info.getCode()) {
			// 现在还没有写修改，如果能修改，必须要判断是否已经有审核人审核，没有才能修改
			result = goodsApplyDAO.update(info);
		} else {
			isadd = true;
			
			info.setAt(time);
			info.setAu(cuCode);
			info.setDeleted(false);
			info.setOc(cuOrganCode);
			result = goodsApplyDAO.add(info);
		}
		
		if (RESULT.SUCCESS != result) 
			throw new Exception("保存申请信息失败");
		
		// 保存明细
		for (ApplyItem item : info.getAdList()) {
			if (null == item.getGn() || Sys.NONE.equals(item.getGn()) || null == item.getCount() && item.getCount().intValue() < 0)
				continue;
				
			if (null == item.getCode()) {
				item.setAcode(info.getCode());
				result = applyItemDAO.add(item);
			} else {
				result = applyItemDAO.update(item);	
			}
			
			if (RESULT.SUCCESS != result) 
				throw new Exception("保存申请明细失败");
		}
		
		// 固定资产要走审核流程
		if (info.getSort().byteValue() == Sys.B_TWO && isadd) {
			// 查询是否有审核流程，有就生成对应的审核状态
			List<ProcessConfig> pcList = processConfigDAO.findByOcBusiness(cu_organCode(request), Sys.B_ONE);
			if (null != pcList && pcList.size() > 0) {
				AuditStatus auditStatus = null;
				for (ProcessConfig p : pcList) {
					auditStatus = new AuditStatus();
					
					auditStatus.setCt(time);
					auditStatus.setCu(cuCode);
					auditStatus.setOc(cuOrganCode);
					auditStatus.setBusiness(Sys.B_ONE);
					auditStatus.setPc(p.getPc());
					auditStatus.setMc(info.getCode());
					auditStatus.setPcc(p.getCode());
					auditStatus.setRc(p.getRc());
					// 默认第一个审核状态的前一个审核节点的审核状态为审核通过
					if (p.getPc().intValue() == 1) 
						auditStatus.setBeforeStatus(Sys.B_ONE);
					
					result = auditStatusDAO.add(auditStatus);
					if (RESULT.SUCCESS != result) 
						throw new Exception("保存审核状态信息失败");
				}
			}
		}
		
		
		if (RESULT.SUCCESS == result) {
			// 消息通知审核人
			Integer rc = auditStatusDAO.findByBusinessOcMc(Sys.B_ONE, cu_organCode(request), info.getCode());	// 获取该机构具有审核申请单的角色编号
			List<UserInfo> userList = userDAO.findByRoleRc(cu_organCode(request), rc);	// 获取有审核角色的所有用户
			if (null != userList && userList.size() > 0) {
				List<Integer> rucs = new ArrayList<Integer>();
				for (UserInfo u : userList) {
					rucs.add(u.getCode());
				}
				String content = mtDAO.applyTofirst(info, cu_realName(request));
				msgDAO.sendToUsers("【" + cu_realName(request) + "】提交申请待审核通知", content, cu_code(request), cu_organCode(request), rucs);
			}
			
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
		
	}


	
	
	@Autowired
	public void setGoodsApplyDAO(MobileGoodsApplyDAO goodsApplyDAO) {
		this.goodsApplyDAO = goodsApplyDAO;
	}

	@Autowired
	public void setApplyItemDAO(MobileGoodsApplyItemDAO applyItemDAO) {
		this.applyItemDAO = applyItemDAO;
	}

	@Autowired
	public void setProcessConfigDAO(ProcessConfigDAO processConfigDAO) {
		this.processConfigDAO = processConfigDAO;
	}

	@Autowired
	public void setAuditStatusDAO(AuditStatusDAO auditStatusDAO) {
		this.auditStatusDAO = auditStatusDAO;
	}

	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Autowired
	public void setMsgDAO(MessageDAO msgDAO) {
		this.msgDAO = msgDAO;
	}

	@Autowired
	public void setMtDAO(MessageTemplateDAO mtDAO) {
		this.mtDAO = mtDAO;
	}
	
	
}
